import re
from flask_restplus import Resource, Namespace, fields, marshal

from common.mixins import DictMixin
from math import ceil
from datetime import datetime

is_dump = False


def get_ip_address(request):
    if request.headers.get('X-Real-Ip'):
        return request.headers.get('X-Real-Ip')
    else:
        return request.remote_addr


def check_phone_number(phone):
    ret = re.match(r"^1[356789]\d{9}$", phone)
    if ret:
        return True
    return False


# 计算pages, 通过 total / per_page 向上取整
def get_pages(per_page, total):
    """The total number of pages"""
    if per_page == 0:
        pages = 0
    else:
        pages = int(ceil(total / float(per_page)))
    return pages


# 自定义序列化
def custom_marshal_pagination(pagination_data):
    list_data = [DictMixin.to_dict(ele.as_dict()) for ele in pagination_data.data]

    return {
        "pages": get_pages(per_page=pagination_data.page_size, total=pagination_data.total),
        "page": pagination_data.page,
        "per_page": pagination_data.page_size,
        "total": pagination_data.total,
        "items": list_data
    }


def custom_marshal_list(list_data):
    return [DictMixin.to_dict(ele.as_dict()) for ele in list_data]


def get_default_date(date):
    if not date:  # 如果没有填写单据日期，默认使用当天的日期，作为单据日期
        return datetime.now().strftime('%Y-%m-%d')
    return date
# def get_pagination_model(api, base_model, model_name='paginate'):
#     return api.model(model_name, {
#         "pages": fields.Integer(),
#         "page": fields.Integer(),
#         "per_page": fields.Integer(),
#         "total": fields.Integer(),
#         "items": fields.Nested(base_model)
#     })


# def add_pagination_and_sort_parser(parser):
#     parser.add_argument('current', dest='current_page', type=int, default=1, help='current_page')
#     parser.add_argument(
#         'pageSize', dest='per_page', type=int, choices=[2, 5, 10, 20, 40], default=20, help='per_page')
#     # todo 根据前端转换
#     parser.add_argument(
#         'sorted_by', type=str, choices=['name', 'create_datetime', 'update_datetime'],
#         default='create_datetime', help='sorted_by')
#     parser.add_argument(
#         'sorted_by_type', type=str, choices=['desc', 'asc'], default='desc', help='sorted_by_type')
#     # 额外增加是否启用
#     parser.add_argument('is_active', type=str, choices=["false", "true"], help='是否启用')
#     return parser
